package com.tgy.JUC.Single;

import java.lang.reflect.Constructor;

/***
 * @ClassName: LazyManUnafse
 * @Description: 利用反射破坏单例模式
 * @Auther: 送你一块二向箔
 * @Date: 17:27 2022/3/15
 * @version : V1.0
 */
public class LazyManUnafse {
    private static LazyManUnafse lazyManUnafse;

    private LazyManUnafse() {
        //改进代码饰得利用反射也不能破坏单例
        synchronized (LazyManUnafse.class){
            if (lazyManUnafse!=null){
                throw new RuntimeException("不要试图利用反射破坏异常");
            }
        }
        System.out.println(Thread.currentThread().getName()+"ok");
    }

    public static LazyManUnafse getInstance() {
        if (lazyManUnafse == null) {
            lazyManUnafse = new LazyManUnafse();
        }
        return lazyManUnafse;
    }

    public static void main(String[] args) throws Exception {
        LazyManUnafse instance = LazyManUnafse.getInstance();
        Constructor<LazyManUnafse> declaredConstructor = LazyManUnafse.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);//无视私有构造器
        LazyManUnafse lazyManUnafse = declaredConstructor.newInstance();
        System.out.println(instance.hashCode());
        System.out.println(lazyManUnafse.hashCode());

    }
}
